// window.onload = function () {
    // alert("1111111111111");
    //

    var Surl = 'http://test.vmbase.scn.weilian.cn/baseStore/getDownloadInfo?enterpriseCode=NJXS';

    function showDialog() {
        document.getElementById("weichat-box").style.display = "block";
    }
    function hideDialog() {
        document.getElementById("weichat-box").style.display = "none";
    }
    var t = new Date().getTime();
    document.querySelector(".download-img").setAttribute("src", "./img/bg1.jpg?token=" + t);
    // document.querySelector(".download-img").setAttribute("src", "./img/bg1.jpg");
    document.querySelector("#njxs").setAttribute("src", "./img/bg2.png?token=" + t);
    var u = navigator.userAgent;
    
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
    //用来校验微信的ua
    var ua = navigator.userAgent.toLowerCase();
    var isWeixin = ua.indexOf('micromessenger') != -1;
    
    if (isWeixin) {
        //提示框
        // showDialog();
        // document.getElementById("confirm").onclick = hideDialog;
        document.querySelector("#njxs").style.display = 'none';
        if(isiOS){
            document.querySelector(".download-img").setAttribute("src", "./img/iOS.png?token=" + t);
        }else{
            document.querySelector(".download-img").setAttribute("src", "./img/Android.png?token=" + t);
        }
    } else {
        if (isiOS) {
            document.querySelector("#download").href = "https://itunes.apple.com/cn/app/%E5%AE%81%E5%AE%B6%E9%B2%9C%E7%94%9F/id1315875095?mt=8";
            // document.querySelector("#download").href = "https://www.pgyer.com/ningjia_ios";
        } else {
            //定位推送下载的apk
            // initScript();
            // document.querySelector("#download").href = "http://113.16.166.75:8990/upload/ningjiaxiansheng.apk";
            $.ajax({
                type: 'GET',
                url: Surl,
                contentType: "application/json",
                dataType: "json",
                success: function (data) { 
                    var storeList = data.data[0];
                    document.querySelector("#download").href = storeList[0].apkDownloadInfo;
                }
            })
        } 
    }

    //加载高德地图script
    function initScript() {
        //判断如果有script就删掉
        if (document.querySelector("#amap-box")){
            // document.body.removeChild(document.querySelector("#amap-box"));
            initMap();
        }else{
            var amapBox = document.createElement("div");
            amapBox.setAttribute("id", "amap-box"); 
            // this.initMap();
            var script1 = document.createElement("script");
            script1.onload = function() {
                var script2 = document.createElement("script");
                script2.onload = function() {
                    initMap();
                }
                script2.src = "http://webapi.amap.com/ui/1.0/main.js";
                amapBox.insertAdjacentElement("beforeend", script2);
            };
            script1.src = "http://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba";
            amapBox.insertAdjacentElement("beforeend", script1);
            document.body.appendChild(amapBox);
        }
    }
    //启动地图
    function initMap() {
        function waitMap (){
            if(AMap.Map){
                keepGoing();
            }else{
                setTimeout(function() {
                    waitMap();
                },300)
            }  
        }
        waitMap();
        function keepGoing() {
            var map = new AMap.Map('allmap', {
                resizeEnable: true,
                zoom: 15,
                center: [108.383765, 22.813923],
                scrollWheel : true
            });
            map.plugin(['AMap.Geolocation', 'AMap.LngLat'], function() {
                //给一个定位过程的loading
                var geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, //是否使用高精度定位，默认:true
                    timeout: 5000, //超过5秒后停止定位，默认：无穷大
                    maximumAge: 0, //定位结果缓存0毫秒，默认：0
                    convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                    showButton: true, //显示定位按钮，默认：true
                    buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
                    buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                    showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                    panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                    zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
                });

                map.addControl(geolocation);
                geolocation.getCurrentPosition();
                //添加定位失败和定位成功的监听事件
                geolocation.on("compvare", function (result) {
                    console.log(result,'rrrrr')
                    getUrl.call(this,result);
                })
                geolocation.on("error", function (err) {
                    console.log(err,'sssss');
                    getUrl.call(this,null);
                });
            })
        }
    }
    //获取下载地址
    function getUrl(result) {
        //通过result确定是否定位到当前位置
        var lnglat = result ? new AMap.LngLat(result.position.lng, result.position.lat) : '';
        //获取门店列表
        $.ajax({
            type: 'GET',
            url: Surl,
            contentType: "application/json",
            dataType: "json",
            success: function (data) { 
                var storeList = data.data[0];
                if(result){
                    var minDistanceStore; 
                    var Arr = [];
                    var minDistance;
                    var minDistanceItem;
                    storeList.map(function(item, index) {
                        item.positionLng && item.positionLat && Arr.push(item);
                    },this);
                    var storeInd = 0;
                    Arr.map(function(item,index) {
                        var arr = [];
                        arr.push(item.positionLng);
                        arr.push(item.positionLat)
                        var myDistance = Number(lnglat.distance(arr));
                        if (index == 0) {
                            minDistance = myDistance;
                            minDistanceItem = item;
                        } else {
                            if (minDistance > myDistance) {
                                minDistance = myDistance;
                                minDistanceItem = item;
                                storeInd = index;
                            }
                        }
                        minDistanceStore = minDistanceItem;     //距离最近的门店
                    },this);
                    //定位成功提供相应的下载地址
                    console.log(navigator)
                    var info = navigator.connection || navigator.mozConnection || navigator.webkitConnection || {};
                    $('#shade').fadeOut();
                    if (info.type === "wifi") {
                        //内网按定位结果分配的下载地址
                        minDistance < 50000 ? document.querySelector("#download").href = minDistanceStore.downloadUrl : document.querySelector("#download").href = storeList[0].apkDownloadInfo;
                    } else {
                        //外网统一的下载地址
                        document.querySelector("#download").href = storeList[0].apkDownloadInfo;
                    }
                }else{
                    //定位失败打开遮罩，显示门店下载列表
                    if(storeList.length == 1){
                        document.querySelector("#download").href = storeList[0].apkDownloadInfo;
                    }else{
                        $('#shade').fadeIn();
                        console.log(storeList,"storeList");
                        var str = '<li>请选择当前所处门店</li>';
                        storeList.map(function(ele,ind) {
                            // str += `<li>
                            //         <a href=${ele.apkDownloadInfo}>
                            //             <img src=${ele.imageUrl ? JSON.parse(ele.imageUrl)[0] : './img/logo.png'} />
                            //         </a>
                            //         <p class='storeName'>${ele.storeName}</p>
                            //         <p class='storePosition'>${ele.province || ''}${ele.province || ''}${ele.distric || ''}${ele.address || ''}</p>
                            //     </li>`;
                            var imageUrl = ele.imageUrl ? JSON.parse(ele.imageUrl)[0] : './img/logo.png';
                            var province = ele.province || '';
                            var distric = ele.distric || '';
                            var address = ele.address || '';
                            str += "<li><a href=" + ele.apkDownloadInfo + "><img src='" + imageUrl + "'/></a><p class='storeName'>" + ele.storeName + "</p><p class='storePosition'>" + province + distric + address + "</li>";
                        })
                        //外网统一的下载地址
                        str += "<li><a href=" + storeList[0].apkDownloadInfo + ">当前不在门店内</a></li>"
                        $('#downloadUrlList>ul').append(str);
                        $('#downloadUrlList').fadeIn();
                    }
                }
            }
        })
    }
// }